<template>
  <div class="upload">
    <van-nav-bar title="修改头像">
      <template #left>
        <i @click="goBack" class="icon iconfont iconbtn_nav_back leftArro"></i>
      </template>
      <template #right>
        <span v-if="isShow" @click="save">保存</span>
      </template>
    </van-nav-bar>
    <div class="icon">
      <van-uploader
        preview-size="200"
        :max-count="1"
        v-model="fileList"
        :after-read="afterRead"
      />
    </div>
  </div>
</template>
<script>
import { uploadImg, apiEditUserInfo } from '@/api/login'
export default {
  data () {
    return {
      id: '',
      isShow: false,
      fileList: [{ url: this.$store.state.userInfo.avatar }]
    }
  },
  methods: {
    goBack () {
      this.$router.go(-1)
    },
    async afterRead (file) {
      console.log(file)

      this.isShow = true
      file.status = 'uploading'
      file.message = '上传中'

      const res = await uploadImg(file.file)
      //   console.log('服务器返回的,', res)

      this.id = res.data[0].id
      this.isShow = true
      file.status = 'done'
      //   apiEditUserInfo({ avatar: res.data.id })
      //   this.$router.push('/info')
    },
    async save () {
      this.$toast.loading({ duration: 0 })
      await apiEditUserInfo({ avatar: this.id })
      this.$store.dispatch('setUserInfo')
      this.$router.push('/info')
      this.$toast.success('上传成功')
    }
  }
}
</script>
<style lang="less">
.upload {
  .van-field__left-icon {
    margin-right: 15px;
  }
  .van-nav-bar__left {
    padding: 0;
  }
  .leftArro {
    font-size: 44px;
  }
  .icon {
    text-align: center;
    margin: 15px;
  }
}
</style>
